#include "ChatServer.h"
#include "ui_ChatServer.h"

ChatServer::ChatServer(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ChatServer)
{
    ui->setupUi(this);

    // 新建服务器
    tcpServer = new QTcpServer(this);

    // 连接信号，处理新连接
    connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newConnection()));

    // 监听端口，打开连接。
    if (!tcpServer->listen(QHostAddress::Any, 6000)) {
        qDebug() << "Error: " << tcpServer->errorString();
    } else {
        qDebug() << "Server started";
    }

}

ChatServer::~ChatServer()
{
    delete ui;
}

void ChatServer::newConnection()
{
    // 建立套接字
    QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
    // 放入列表方便管理：
    clients << clientSocket;
    // 连接信号，准备读取和断开：
    connect(clientSocket, SIGNAL(readyRead()), this, SLOT(readyRead()));
    connect(clientSocket, SIGNAL(disconnected()), this, SLOT(disconnected()));
    // 测试用：显示连接
    qDebug() << "New client from:" << clientSocket->peerAddress().toString();
    ui->MessageLabel->setText("New cliented");
}

void ChatServer::readyRead()
{
    // 建立套接字：
    QTcpSocket *clientSocket = (QTcpSocket*)sender();
    // 建立输入流：
    QTextStream in(clientSocket);
    // 只要没结束，就一直读取：
    while (!in.atEnd()) {
        // 读取一行
        QString message = in.readLine();
        qDebug() << "Message from client:" << message;

        auto msgList = message.split(":");
        ui->ChatEdit->append("Message from ");
        for(auto msg : msgList)
        {
            ui->ChatEdit->append(msg);
        }
        ui->ChatEdit->append("------------------------------\n");
        // 遍历客户端列表，将数据同步到所有客户端。
        foreach (QTcpSocket *socket, clients) {
            if (socket != clientSocket) {
                QTextStream out(socket);
                out << message << "\n";
            }
        }
    }
}

void ChatServer::disconnected()
{
    QTcpSocket *clientSocket = (QTcpSocket*)sender();
    clients.removeOne(clientSocket);
    qDebug() << "Client from:" << clientSocket->peerAddress().toString() << "disconnected.";
    ui->MessageLabel->setText("Client from:"+clientSocket->peerAddress().toString()+"disconnected.");
}

